## Kritiker provides a private API for people they allow.
## - Needed argument is IMDB ID
## - Required options is kritiker_token

require 'oj'

module Shin
  module Reviews
    class Kritiker
      
      def new
        self
      end
      
      def find(h = {})
        raise MissingArgument, "You are missing the argument 'imdb' or 'kritiker_token' which is required to use this source." unless h[:imdb] != "" and Shin.get[:kritiker_token] != ""
        
        # We got the needed things
        response = Base.get('http://api.kritiker.se/film/?imdb='+h[:imdb]+'&token='+Shin.get[:kritiker_token])

        data = Oj.load(response.body) rescue nil
        raise NotJSON, "Returned data isn't JSON. Couldn't parse it." if data == nil

        year = data['datum'][/^(\d\d\d\d)/, 1].to_i unless data['datum'][/^(\d\d\d\d)/, 1].to_i == 0
        {name: data['titel'], year: year, title: nil, rating: data['medelbetyg'].gsub(",", ".").to_f, url: data['kritiker'], votes: data['antalrecensioner'].to_i}.to_hashugar
      end
      
      class NotJSON          < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end
